#include <iostream>
#include <unistd.h>
#include <pthread.h>
int cnt = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  // 全局锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;     // 全局条件变量
void *Count(void *arg) {
    pthread_detach(pthread_self());   // 线程分离
    u_int64_t number = (u_int64_t)arg;
    while(1)
    {   
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);   // 该函数会让当前线程阻塞并且释放mutex(如果持有)
        std::cout << "thread " << number  << ",cnt: " << cnt ++ << std::endl;
        pthread_mutex_unlock(&mutex);
    }
    

}

int main() {
    for(u_int64_t i = 0; i < 5; i++){
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void*)i);  // 这里的i不能传地址，应为 不然在子线程和主线程会获取到同一个i
    }
    sleep(2);


    while(1){
        sleep(1);
        pthread_cond_signal(&cond); // 唤醒一个线程
    }
}